<template>
  <div
    v-show="isVisible && !isMinimized"
    ref="windowRef"
    class="resizable-window"
    :class="{
      minimized: isMinimized,
      fullscreen: isFullscreen,
      dragging: isDragging,
    }"
    :style="windowStyle"
    @mousedown="startDrag"
  >
    <!-- 控制按钮区域 -->
    <div class="window-controls" @mousedown.stop>
      <button
        class="control-btn"
        @click="toggleMinimize"
        :title="isMinimized ? '还原' : '最小化'"
      >
        <el-icon v-if="isMinimized"><EditPen /></el-icon>
        <el-icon v-else><Minus /></el-icon>
      </button>
      <button
        class="control-btn"
        @click="toggleFullscreen"
        :title="isFullscreen ? '退出全屏' : '全屏'"
      >
        <el-icon v-if="isFullscreen"><CopyDocument /></el-icon>
        <el-icon v-else><FullScreen /></el-icon>
      </button>
      <button class="control-btn" @click="handleExitRoom" title="退出房间">
        <el-icon><Close /></el-icon>
      </button>
    </div>

    <!-- 窗口内容区域 -->
    <div class="window-content" v-show="!isMinimized">
      <Room />
    </div>

    <!-- 调整大小的控制点 -->
    <div
      v-for="handle in resizeHandles"
      :key="handle.direction"
      :class="['resize-handle', `resize-${handle.direction}`]"
      @mousedown.stop="startResize($event, handle.direction)"
      v-show="!isMinimized && !isFullscreen"
    ></div>
  </div>

  <!-- 最小化状态下的按钮 -->
  <div
    v-if="isVisible"
    v-show="isMinimized"
    class="minimized-window-button"
    :style="minimizedButtonStyle"
    @click="handleMinimizedClick"
    @mousedown="startDragMinimized"
  >
    <EditPen class="minimized-icon" />
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  computed,
  onMounted,
  onBeforeUnmount,
  provide,
} from "vue";
import { EditPen } from "@element-plus/icons-vue";
import Room from "./Room.vue";
import { useStudyRoomStore } from "@/stores";
import { ElMessageBox } from "element-plus";

// 定义组件属性
const props = defineProps({
  initialX: {
    type: Number,
    default: 0,
  },
  initialY: {
    type: Number,
    default: 0,
  },
  initialWidth: {
    type: Number,
    default: 0,
  },
  initialHeight: {
    type: Number,
    default: 0,
  },
  minWidth: {
    type: Number,
    default: 200,
  },
  minHeight: {
    type: Number,
    default: 150,
  },
});

// 响应式数据
const windowRef = ref<HTMLElement | null>(null);
const isVisible = ref(true);
const isMinimized = ref(false);
const isFullscreen = ref(false); // 默认窗口模式
const isDragging = ref(false);
const isResizing = ref(false);
const isMouseDownOnMinimized = ref(false); // 用于防止拖拽后触发点击事件
const roomStore = useStudyRoomStore();
// 窗口状态
const windowState = reactive({
  x: props.initialX,
  y: props.initialY,
  width: props.initialWidth || window.innerWidth * 0.8, // 默认80%宽度
  height: props.initialHeight || window.innerHeight * 0.8, // 默认80%高度
  minimizedX: 0,
  minimizedY: 0,
});

const handleOutsideClick = (e: MouseEvent) => {
  // 只在非全屏模式下处理
  if (!isFullscreen.value && !isMinimized.value && windowRef.value) {
    // 检查点击是否在窗口外部
    const target = e.target as HTMLElement;
    
    // 检查点击目标是否是Element Plus的模态框或其子元素
    const isMessageBox = target.closest('.el-message-box, .el-overlay, .el-popup-parent--hidden');
    
    // 如果点击的是模态框，则不执行最小化操作
    if (isMessageBox) {
      return;
    }
    
    if (windowRef.value && !windowRef.value.contains(target)) {
      minimizeWindow();
    }
  }
};
// 添加document点击事件监听器
const handleClickOutside = (e: MouseEvent) => {
  handleOutsideClick(e);
};

onMounted(() => {
  document.addEventListener('click', handleClickOutside, true);
});

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside, true);
});

const handleExitRoom = () => {
  ElMessageBox.confirm("是否要退出自习室？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      roomStore.leaveRoom();
    })
    .catch(() => {});
};


// 保存最小化前的窗口状态
const savedWindowState = reactive({
  x: 0,
  y: 0,
  width: 0,
  height: 0,
  isFullscreen: false,
});

// 保存最小化按钮的位置
const savedMinimizedPosition = reactive({
  x: window.innerWidth - 70,
  y: window.innerHeight / 2,
});

// 拖拽状态
const dragState = reactive({
  startX: 0,
  startY: 0,
  startLeft: 0,
  startTop: 0,
});

// 调整大小状态
const resizeState = reactive({
  startX: 0,
  startY: 0,
  startWidth: 0,
  startHeight: 0,
  startLeft: 0,
  startTop: 0,
});

// 粘滞感参数
const snapThreshold = 20; // 吸附阈值

// 计算窗口样式
const windowStyle = computed(() => {
  if (isFullscreen.value) {
    return {
      width: "100vw",
      height: "100vh",
      left: "0px",
      top: "0px",
    };
  }

  return {
    left: `${windowState.x}px`,
    top: `${windowState.y}px`,
    width: `${windowState.width}px`,
    height: `${windowState.height}px`,
    transition: isDragging.value || isResizing.value ? "none" : "all 0.3s ease", // 拖拽时禁用过渡动画
  };
});

// 最小化按钮样式
const minimizedButtonStyle = computed(() => {
  return {
    left: `${windowState.minimizedX}px`,
    top: `${windowState.minimizedY}px`,
  };
});

// 调整大小控制点
const resizeHandles = computed(() => [
  { direction: "nw" },
  { direction: "n" },
  { direction: "ne" },
  { direction: "w" },
  { direction: "e" },
  { direction: "sw" },
  { direction: "s" },
  { direction: "se" },
]);

// 检查是否为展开状态
const isExpanded = computed(() => !isMinimized.value && !isFullscreen.value);

// 拖拽开始
const startDrag = (e: MouseEvent) => {
  if (isFullscreen.value) return;

  isDragging.value = true;
  dragState.startX = e.clientX;
  dragState.startY = e.clientY;
  dragState.startLeft = windowState.x;
  dragState.startTop = windowState.y;

  document.addEventListener("mousemove", onDrag);
  document.addEventListener("mouseup", stopDrag);
};

// 拖拽最小化按钮
const startDragMinimized = (e: MouseEvent) => {
  isMouseDownOnMinimized.value = true;
  isDragging.value = true;
  dragState.startX = e.clientX;
  dragState.startY = e.clientY;
  dragState.startLeft = windowState.minimizedX;
  dragState.startTop = windowState.minimizedY;

  // 添加一个标志来判断是否发生了拖拽
  let isMoved = false;
  const moveThreshold = 5; // 5像素的阈值

  const onDragMinimized = (e: MouseEvent) => {
    if (!isDragging.value) return;

    const dx = e.clientX - dragState.startX;
    const dy = e.clientY - dragState.startY;

    // 如果移动超过阈值，标记为发生了拖拽
    if (
      !isMoved &&
      (Math.abs(dx) > moveThreshold || Math.abs(dy) > moveThreshold)
    ) {
      isMoved = true;
    }

    let newX = dragState.startLeft + dx;
    let newY = dragState.startTop + dy;

    windowState.minimizedX = newX;
    windowState.minimizedY = newY;

    // 防止按钮被拖出屏幕边界
    const buttonSize = 50;
    if (windowState.minimizedX < 0) windowState.minimizedX = 0;
    if (windowState.minimizedY < 0) windowState.minimizedY = 0;
    if (windowState.minimizedX > window.innerWidth - buttonSize)
      windowState.minimizedX = window.innerWidth - buttonSize;
    if (windowState.minimizedY > window.innerHeight - buttonSize)
      windowState.minimizedY = window.innerHeight - buttonSize;
  };

  const stopDragMinimized = () => {
    isDragging.value = false;
    // 保存最小化按钮位置
    savedMinimizedPosition.x = windowState.minimizedX;
    savedMinimizedPosition.y = windowState.minimizedY;
    // 应用边缘吸附
    snapMinimizedToEdges();

    // 根据是否发生移动来决定是否阻止点击事件
    if (isMoved) {
      // 设置一个短暂的标志来阻止点击事件
      const clickPreventedFlag = setTimeout(() => {
        isMouseDownOnMinimized.value = false;
      }, 200);
    } else {
      // 没有移动，立即允许点击事件
      isMouseDownOnMinimized.value = false;
    }

    document.removeEventListener("mousemove", onDragMinimized);
    document.removeEventListener("mouseup", stopDragMinimized);
  };

  document.addEventListener("mousemove", onDragMinimized);
  document.addEventListener("mouseup", stopDragMinimized);
};
// 拖拽中
const onDrag = (e: MouseEvent) => {
  if (!isDragging.value) return;

  const dx = e.clientX - dragState.startX;
  const dy = e.clientY - dragState.startY;

  let newX = dragState.startLeft + dx;
  let newY = dragState.startTop + dy;

  windowState.x = newX;
  windowState.y = newY;

  // 防止窗口被拖出屏幕边界
  if (windowState.x < 0) windowState.x = 0;
  if (windowState.y < 0) windowState.y = 0;
};

// 停止拖拽
const stopDrag = () => {
  isDragging.value = false;

  // 应用边缘吸附
  if (!isFullscreen.value) {
    snapToEdges();
  }

  document.removeEventListener("mousemove", onDrag);
  document.removeEventListener("mouseup", stopDrag);
};

// 边缘吸附
const snapToEdges = () => {
  const rightEdge = window.innerWidth - windowState.width;
  const bottomEdge = window.innerHeight - windowState.height;

  // 右边缘吸附
  if (Math.abs(windowState.x - rightEdge) < snapThreshold) {
    windowState.x = rightEdge;
  }

  // 左边缘吸附
  if (Math.abs(windowState.x) < snapThreshold) {
    windowState.x = 0;
  }

  // 下边缘吸附
  if (Math.abs(windowState.y - bottomEdge) < snapThreshold) {
    windowState.y = bottomEdge;
  }

  // 上边缘吸附
  if (Math.abs(windowState.y) < snapThreshold) {
    windowState.y = 0;
  }
};

// 最小化按钮边缘吸附
const snapMinimizedToEdges = () => {
  const buttonSize = 50;
  const rightEdge = window.innerWidth - buttonSize;
  const bottomEdge = window.innerHeight - buttonSize;

  // 右边缘吸附
  if (Math.abs(windowState.minimizedX - rightEdge) < snapThreshold) {
    windowState.minimizedX = rightEdge;
  }

  // 左边缘吸附
  if (Math.abs(windowState.minimizedX) < snapThreshold) {
    windowState.minimizedX = 0;
  }

  // 下边缘吸附
  if (Math.abs(windowState.minimizedY - bottomEdge) < snapThreshold) {
    windowState.minimizedY = bottomEdge;
  }

  // 上边缘吸附
  if (Math.abs(windowState.minimizedY) < snapThreshold) {
    windowState.minimizedY = 0;
  }
};

// 开始调整大小
const startResize = (e: MouseEvent, direction: string) => {
  e.preventDefault();
  isResizing.value = true;

  resizeState.startX = e.clientX;
  resizeState.startY = e.clientY;
  resizeState.startWidth = windowState.width;
  resizeState.startHeight = windowState.height;
  resizeState.startLeft = windowState.x;
  resizeState.startTop = windowState.y;

  document.body.style.cursor = getResizeCursor(direction);

  const onResize = (e: MouseEvent) => {
    if (!isResizing.value) return;

    const dx = e.clientX - resizeState.startX;
    const dy = e.clientY - resizeState.startY;

    resizeWindow(direction, dx, dy);
  };

  const stopResize = () => {
    isResizing.value = false;
    document.body.style.cursor = "";

    // 调整大小结束后应用边缘吸附
    if (!isFullscreen.value) {
      snapToEdges();
    }

    document.removeEventListener("mousemove", onResize);
    document.removeEventListener("mouseup", stopResize);
  };

  document.addEventListener("mousemove", onResize);
  document.addEventListener("mouseup", stopResize);
};

// 调整窗口大小
const resizeWindow = (direction: string, dx: number, dy: number) => {
  let newWidth = resizeState.startWidth;
  let newHeight = resizeState.startHeight;
  let newX = resizeState.startLeft;
  let newY = resizeState.startTop;

  // 水平调整
  if (direction.includes("w")) {
    // 西边调整
    newWidth = resizeState.startWidth - dx;
    newX = resizeState.startLeft + dx;
  } else if (direction.includes("e")) {
    // 东边调整
    newWidth = resizeState.startWidth + dx;
  }

  // 垂直调整
  if (direction.includes("n")) {
    // 北边调整
    newHeight = resizeState.startHeight - dy;
    newY = resizeState.startTop + dy;
  } else if (direction.includes("s")) {
    // 南边调整
    newHeight = resizeState.startHeight + dy;
  }

  // 限制最小尺寸
  if (newWidth < props.minWidth) {
    newWidth = props.minWidth;
    if (direction.includes("w")) {
      newX = resizeState.startLeft + (resizeState.startWidth - props.minWidth);
    }
  }

  if (newHeight < props.minHeight) {
    newHeight = props.minHeight;
    if (direction.includes("n")) {
      newY = resizeState.startTop + (resizeState.startHeight - props.minHeight);
    }
  }

  // 更新窗口尺寸和位置
  windowState.width = newWidth;
  windowState.height = newHeight;
  windowState.x = newX;
  windowState.y = newY;
};

// 获取调整大小的光标样式
const getResizeCursor = (direction: string) => {
  const cursors: Record<string, string> = {
    n: "ns-resize",
    s: "ns-resize",
    w: "ew-resize",
    e: "ew-resize",
    nw: "nwse-resize",
    ne: "nesw-resize",
    sw: "nesw-resize",
    se: "nwse-resize",
  };
  return cursors[direction] || "default";
};
// 切换最小化
const toggleMinimize = () => {
  if (isMinimized.value) {
    restoreWindow();
  } else {
    minimizeWindow();
  }
};

// 最小化窗口
const minimizeWindow = () => {
  // 保存当前窗口状态
  savedWindowState.x = windowState.x;
  savedWindowState.y = windowState.y;
  savedWindowState.width = windowState.width;
  savedWindowState.height = windowState.height;
  savedWindowState.isFullscreen = isFullscreen.value;
  // 使用之前保存的位置或默认位置
  windowState.minimizedX = savedMinimizedPosition.x;
  windowState.minimizedY = savedMinimizedPosition.y;
  isMinimized.value = true;
};

// 处理最小化按钮点击
const handleMinimizedClick = (e: MouseEvent) => {
  // 只有在非拖拽状态下才触发还原
  if (!isMouseDownOnMinimized.value) {
    restoreWindow();
  }
  e.preventDefault();
  e.stopPropagation();
};

// 还原窗口
const restoreWindow = () => {
  // 恢复之前保存的状态
  windowState.x = savedWindowState.x;
  windowState.y = savedWindowState.y;
  windowState.width = savedWindowState.width;
  windowState.height = savedWindowState.height;
  isFullscreen.value = savedWindowState.isFullscreen;
  isMinimized.value = false;
};

// 切换全屏
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value;
};

// 处理窗口大小变化
const handleResize = () => {
  if (!windowRef.value) return;

  // 如果是全屏状态，更新为新的窗口尺寸
  if (isFullscreen.value) {
    windowState.width = window.innerWidth;
    windowState.height = window.innerHeight;
  }
  // 防止窗口移出屏幕
  else if (!isMinimized.value) {
    if (windowState.x + windowState.width > window.innerWidth) {
      windowState.x = window.innerWidth - windowState.width;
    }

    if (windowState.y + windowState.height > window.innerHeight) {
      windowState.y = window.innerHeight - windowState.height;
    }

    if (windowState.x < 0) windowState.x = 0;
    if (windowState.y < 0) windowState.y = 0;
  }

  // 更新默认最小化位置
  savedMinimizedPosition.x = window.innerWidth - 70;
  savedMinimizedPosition.y = window.innerHeight / 2;
};

// 组件挂载时
onMounted(() => {
  // 设置窗口初始位置为屏幕正中
  windowState.x = (window.innerWidth - windowState.width) / 2;
  windowState.y = (window.innerHeight - windowState.height) / 2;

  window.addEventListener("resize", handleResize);
  handleResize();
});

// 组件卸载前
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
});

//传递最小化方法minimizeWindow给子组件
provide("minimizeWindow", minimizeWindow);
</script>

<style scoped>
.resizable-window {
  position: fixed;
  background: white;
  border-radius: 8px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  z-index: 2000;
  overflow: hidden;
  border: 1px solid #e2e8f0;
  /* 移除了transition，改为在计算属性中动态控制 */
}

.resizable-window.fullscreen {
  border-radius: 0;
  box-shadow: none;
  z-index: 3000;
}

/* 控制按钮 */
.window-controls {
  position: absolute;
  top: 8px;
  left: 8px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  z-index: 2001;
  gap: 4px;
}

.control-btn {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  border: none;
  background: #f1f5f9;
  color: #64748b;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  transition: all 0.2s;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.control-btn:hover {
  background: #e2e8f0;
  transform: scale(1.1);
}

.close-btn:hover {
  background: #ef4444;
  color: white;
}

.resizable-window.fullscreen .window-controls {
  top: 8px;
  left: 8px;
  transform: none;
}

/* 窗口内容 */
.window-content {
  height: 100%;
  padding: 1rem;
  overflow: auto;
}

/* 调整大小控制点 */
.resize-handle {
  position: absolute;
  z-index: 2001;
}

/* 角落控制点 */
.resize-nw {
  top: -5px;
  left: -5px;
  width: 15px;
  height: 15px;
  cursor: nw-resize;
}

.resize-ne {
  top: -5px;
  right: -5px;
  width: 15px;
  height: 15px;
  cursor: ne-resize;
}

.resize-sw {
  bottom: -5px;
  left: -5px;
  width: 15px;
  height: 15px;
  cursor: sw-resize;
}

.resize-se {
  bottom: -5px;
  right: -5px;
  width: 15px;
  height: 15px;
  cursor: se-resize;
}

/* 边缘控制点 */
.resize-n {
  top: -5px;
  left: 10px;
  right: 10px;
  height: 10px;
  cursor: n-resize;
}

.resize-s {
  bottom: -5px;
  left: 10px;
  right: 10px;
  height: 10px;
  cursor: s-resize;
}

.resize-w {
  left: -5px;
  top: 10px;
  bottom: 10px;
  width: 10px;
  cursor: w-resize;
}

.resize-e {
  right: -5px;
  top: 10px;
  bottom: 10px;
  width: 10px;
  cursor: e-resize;
}

/* 最小化按钮 */
.minimized-window-button {
  position: fixed;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  cursor: pointer;
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #e2e8f0;
  transition: transform 0.2s ease;
}

.minimized-window-button:hover {
  transform: scale(1.1);
}

.minimized-icon {
  width: 30px;
  height: 30px;
  color: #64748b;
}
</style>
